import "./planadd.less";
import { View, Text, Button } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useCallback, useState } from "react";
import { TPlanMotion, TPlan, TValue } from "@/types";
import { deepClone, rpxToPx } from "@/utils";
import { RecordWay } from "@/utils/options";
import { COLORS } from "@/utils/constants";

import FormInput from "@/components/FormInput";
import RadioText from "@/components/RadioText";
import Tag from "@/components/Tag";
import Empty from "@/components/Empty";
import useAccordion from "@/hooks/useAccordion";
import PlusIcon from "@/components/Icons/PlusIcon";

import MotionSets from "./MotionSets";
import PlanMotion from "./PlanMotion";
import MotionSelector from "./MotionSelector";
import SwipeableCard from "@/components/SwipeableCard";
import { useEffect } from "react";
import { addPlan, getPlan, updatePlan } from "@/request";
import Tabs from "@/components/Tabs";

import MotionForSort from "./MotionForSort";
import MotionDetail from "../motion/MotionDetail";
import { PopupProvider, usePopup } from "@/store/popup";

const ITEM_HEIGHT = rpxToPx(12 * 3 + 30 * 4);

const formatMotion = (i: TPlanMotion) => ({
  uuid: i.uuid,
  motionId: i.motionId,
  recordWay: i.recordWay,
  setsType: i.setsType,
  unit: i.unit,
  sets: i.sets,
  innerRest: Number(i.innerRest),
  outerRest: Number(i.outerRest),
});

const PlanAdd = () => {
  const [mode, setMode] = useState("add");
  const { openPopup, closePopup } = usePopup();

  const [actionMode, setActionMode] = useState<TValue>(0);
  const { active, toggleActive } = useAccordion(); // 展开折叠
  const [data, setData] = useState<TPlan>({
    name: "",
    motions: [],
  });

  useEffect(() => {
    const params = Taro.getCurrentInstance().router?.params;
    let mode = params?.mode;
    let id = params?.id;
    if (mode) {
      setMode(mode);
    }
    if (mode === "edit" && id) {
      handleGetData(id);
    }
    Taro.setNavigationBarTitle({
      title: mode === "edit" ? "编辑计划" : "新建计划",
    });
  }, []);

  const handleGetData = async (id: string) => {
    const res: TPlan = await getPlan(id);
    setData(res);
  };

  const handleSubmit = async () => {
    data.motions.forEach((i) => {
      i.sets = i.sets.map((j) => j.map((k) => Number(k)));
    });

    if (mode === "add") {
      await addPlan({
        ...data,
        motions: data.motions.map(formatMotion),
      });
    }

    if (mode === "edit") {
      await updatePlan({
        _id: data._id,
        name: data.name,
        motions: data.motions.map(formatMotion),
      });
    }

    Taro.navigateBack();
  };

  const handleSelectMotions = (motions) => {
    setData({
      ...data,
      motions: [...data.motions, ...motions],
    });
  };
  const handleChangeMotion = (
    uuid: string,
    name: string,
    value?,
    index?: number
  ) => {
    if (name === "delete") {
      setData((prev) => ({
        ...prev,
        motions: prev.motions.filter((i) => i.uuid !== uuid),
      }));
      return;
    } else {
      setData((prev) => ({
        ...prev,
        motions: prev.motions.map((i) => {
          if (i.uuid === uuid) {
            let obj = deepClone(i);
            switch (name) {
              case "recordWay":
                if (value === 0) {
                  obj.sets = [[0, 10]];
                  obj.setsType = 0;
                  obj.unit = 0;
                } else {
                  obj.sets = [];
                  obj.innerRest = 0;
                }
                obj[name] = value;
                break;
              case "sets":
                obj[name][index] = value;
                break;
              case "addSet":
                obj.sets.splice(index + 1, 0, [0, 10]);
                break;
              case "delSet":
                obj.sets.splice(index, 1);
                break;
              case "toggleinnerRest":
                obj.openInner = !obj.openInner;
                if (obj.openInner) {
                  obj.innerRest = 30;
                } else {
                  obj.innerRest = 0;
                }
                break;
              case "toggleouterRest":
                obj.openOuter = !obj.openOuter;
                if (obj.openOuter) {
                  obj.outerRest = 30;
                } else {
                  obj.outerRest = 0;
                }
                break;
              default:
                obj[name] = value;
                break;
            }
            return obj;
          }
          return i;
        }),
      }));
    }
  };

  const handleChangeSort = useCallback((motions) => {
    setData((prev) => ({
      ...prev,
      motions,
    }));
  }, []);

  const handleOpenDetail = (id: string) => {
    openPopup({
      getNode: () => (
        <MotionDetail onClose={closePopup} id={id} canHandle={false} />
      ),
    });
  };

  const radio = [
    { label: "编辑", value: 0 },
    { label: "排序", value: 1 },
  ];

  const issort = actionMode === 1;

  return (
    <PopupProvider>
      <View className="planadd">
        <View className="form-card">
          <FormInput
            label="计划名称"
            value={data.name}
            placeholder="请输入计划名称"
            onChange={(value) => {
              setData((prev) => ({ ...prev, name: value }));
            }}
          />
        </View>
        <View className="planadd-motions-header">
          <View className="flex-align">
            <Text style={{ fontSize: "18px" }}>动作组</Text>
            <Tag small>{data.motions.length}</Tag>
          </View>
          <Tabs
            options={radio}
            onChange={(v) => {
              setActionMode(v);
              if (v === 1) {
                toggleActive("");
              }
            }}
            value={actionMode}
          />
          <View className="flex">
            <MotionSelector
              onSelect={handleSelectMotions}
              trigger={
                <View className="addmotion-button">
                  <PlusIcon type="primary" size={1} />
                  <Text>动作</Text>
                </View>
              }
            />
          </View>
        </View>

        {data.motions.length === 0 ? (
          <Empty type="white" text="当前动作组为空，快去添加吧！" />
        ) : (
          <View>
            {data.motions.map((item, index) => {
              if (issort) {
                return (
                  <MotionForSort
                    itemHeight={ITEM_HEIGHT}
                    dataSource={data.motions}
                    key={item.uuid}
                    item={{ index, ...item }}
                    onChange={handleChangeSort}
                  />
                );
              } else {
                const isSelected = active === item.uuid;
                return (
                  <SwipeableCard
                    style={{ marginBottom: Taro.pxTransform(12) }}
                    onDelete={() => handleChangeMotion(item.uuid, "delete")}
                  >
                    <PlanMotion
                      key={item.uuid}
                      item={item}
                      onClick={() => {
                        toggleActive(item.uuid);
                      }}
                      onOpenDetail={handleOpenDetail}
                      style={{
                        borderColor: isSelected ? COLORS.primary : "none",
                        marginBottom: 0,
                      }}
                      {...(isSelected
                        ? {
                            headerLeftSlot: (
                              <View className="flex">
                                <RadioText
                                  key="recordWay"
                                  value={item.recordWay}
                                  options={RecordWay}
                                  onClick={(e) => e.stopPropagation()}
                                  onChange={handleChangeMotion.bind(
                                    null,
                                    item.uuid,
                                    "recordWay"
                                  )}
                                />
                              </View>
                            ),
                            setsSlot: (
                              <MotionSets
                                motion={item}
                                onChange={handleChangeMotion.bind(
                                  null,
                                  item.uuid
                                )}
                              />
                            ),
                            headerRightSlot: " ",
                          }
                        : {})}
                    />
                  </SwipeableCard>
                );
              }
            })}
          </View>
        )}
        <Button onClick={handleSubmit} className="primary-button">
          确定
        </Button>
      </View>
    </PopupProvider>
  );
};

export default PlanAdd;
